package cn.youyeku.zsxh.ui.home;//package cn.youyeku.zsxh.ui;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Properties;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.youyeku.zsxh.R;
import cn.youyeku.zsxh.Utils.AppConfig;
import cn.youyeku.zsxh.Utils.LogUtils;
import cn.youyeku.zsxh.api.ResponseStatus;
import cn.youyeku.zsxh.api.XhApi;
import cn.youyeku.zsxh.app;
import cn.youyeku.zsxh.ui.UIControl;
import cn.youyeku.zsxh.ui.activity.ABS.BaseActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * Created by youye on 17-3-17.
 */

public class LoginActivity extends BaseActivity implements View.OnClickListener, TextView.OnEditorActionListener, TextWatcher {


    @BindView(R.id.login_et_email)
    AutoCompleteTextView login_email;
    @BindView(R.id.login_et_password)
    EditText login_et_password;
    @BindView(R.id.bt_login)
    Button bt_login;
    @BindView(R.id.login_teacher)
    RadioButton mLoginTeacher;
    @BindView(R.id.login_student)
    RadioButton mLoginStudent;
    @BindView(R.id.login_group)
    RadioGroup mLoginGroup;
    private ProgressDialog mLoginProgressDialog;
    private InputMethodManager imm;
    public static boolean isLoging = true;
    private boolean login_teacher;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_user_login);
        ButterKnife.bind(this);
        imm = (InputMethodManager) getSystemService(
                Context.INPUT_METHOD_SERVICE);

        mLoginStudent.setChecked(true);
        mLoginGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

                switch (checkedId){
                    case R.id.login_teacher:
                        login_teacher=true;
                        break;
                    case R.id.login_student:
                        login_teacher=false;
                        break;
                }
                LogUtils.w(String.valueOf(login_teacher));
            }

        });


    }

    private void initView() {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {

    }


    //点击登录按钮
    @Override
    @OnClick({R.id.bt_login, R.id.login_teacher, R.id.login_student, R.id.login_group})
    public void onClick(View v) {
        imm.hideSoftInputFromWindow(login_et_password.getWindowToken(), 0);

        switch (v.getId()) {
            case R.id.bt_login:
                checkLogin();
                break;

        }

    }

    //
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        //在输入法里点击了“完成”，则去登录
        if (actionId == EditorInfo.IME_ACTION_DONE) {
//            checkLogin();
            //将输入法隐藏

            imm.hideSoftInputFromWindow(login_et_password.getWindowToken(), 0);
            return true;
        }

        return false;
    }

    //输入完成后全部主要入口
    private void checkLogin() {
        String email = login_email.getText().toString();
        String passwd = login_et_password.getText().toString();

        //检查用户输入的参数


        login(email, passwd);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        menu.add(Menu.NONE, Menu.FIRST, Menu.NONE, "注册")
                .setEnabled(true)
                .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);


        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case Menu.FIRST:
                UIControl.showRegisterActivity(getApplicationContext());
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void login(String email, String passwd) {
        isLoging = false;

        XhApi.login(email, passwd, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {


                try {
                    JSONObject object = new JSONObject(response.body().string());
                    app.backgroundThreadShortToast(object.getString("message"));
                    LogUtils.w(String.valueOf(object.getString("data")));
                    int code = object.getInt("code");
                    if (code == 200) {
                        JSONObject object1 = (JSONObject) object.get("data");
                        String uid = object1.getString("uid");
                        String nick_name = object1.getString("nick_name");
                        String is_teacher = object1.getString("is_teacher");

                        AppConfig.CONF_USER_ID = uid;
                        AppConfig.CONF_USER_NICK_NAME = nick_name;
                        AppConfig.CONF_IS_TEACHER= is_teacher.equals("1");
                        Properties ps = AppConfig.getProps();
                        ps.setProperty("CONF_USER_ID", uid);
                        ps.setProperty("CONF_USER_NICK_NAME", nick_name);
                        ps.setProperty("CONF_IS_TEACHER", String.valueOf(AppConfig.CONF_IS_TEACHER) );

                        AppConfig.set(ps);
                        LogUtils.w("=========="+AppConfig.CONF_IS_TEACHER);
                        if (login_teacher) {
                            if(is_teacher.equals("1")){
                                UIControl.showTeacherMain(getApplicationContext());
                            }else {
                                app.backgroundThreadShortToast("对不起 你不是教师用户");
                            }

                        } else {
                            UIControl.showMain(getApplicationContext());
                        }


                    } else if (code == ResponseStatus.STATUS_UNACTIVE) {
                        JSONObject object1 = (JSONObject) object.get("data");
                        String uid = object1.getString("uid");
                        String nick_name = object1.getString("nick_name");

                        AppConfig.CONF_USER_ID = uid;
                        AppConfig.CONF_USER_NICK_NAME = nick_name;
                        Properties ps = AppConfig.getProps();
                        ps.setProperty("CONF_USER_ID", uid);
                        ps.setProperty("CONF_USER_NICK_NAME", nick_name);
                        AppConfig.set(ps);
                        UIControl.showUnActiveActivity(getApplicationContext());
                        LogUtils.w(uid + "        " + nick_name);
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });


    }
}
